package com.qianli.cashmama.trade.common.utils;

import java.io.*;

/**
 * @BelongsProject: cashmama-trade-center
 * @BelongsPackage: com.qianli.cashmama.trade.common.utils
 * @Author: zhihaoxie
 * @CreateTime: 2018-08-01 19:39
 * @Description: 文件系统文件操作工具类
 */
public class FileUtil {

    /** *//**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;


    /** *//**
     * <p>
     * 二进制数据写文件
     * </p>
     *
     * @param bytes 二进制数据
     * @param filePath 文件生成目录
     */
    public static void byteArrayToFile(byte[] bytes, String filePath) {
        InputStream in = new ByteArrayInputStream(bytes);
        File destFile = new File(filePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        OutputStream out = null;
        try {
            destFile.createNewFile();
            out = new FileOutputStream(destFile);
            byte[] cache = new byte[CACHE_SIZE];
            int nRead = 0;
            while ((nRead = in.read(cache)) != -1) {
                out.write(cache, 0, nRead);
                out.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if ( out != null ) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }

            if ( in != null ) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
